import { StatusCodes } from 'http-status-codes';
import logger from '../config/logger.js';

/**
 * 基础控制器类，所有控制器都继承此类
 */
class BaseController {
  constructor(service) {
    this.service = service;
    this.logger = logger.child({ controller: this.constructor.name });
  }

  /**
   * 成功响应
   * @param {Object} res - Express响应对象
   * @param {*} data - 响应数据
   * @param {string} message - 成功消息
   * @param {number} statusCode - HTTP状态码，默认为200
   */
  success(res, data, message = '操作成功', statusCode = StatusCodes.OK) {
    res.status(statusCode).json({
      success: true,
      message,
      data,
    });
  }

  /**
   * 错误响应
   * @param {Object} res - Express响应对象
   * @param {string} message - 错误消息
   * @param {number} statusCode - HTTP状态码，默认为400
   * @param {Object} error - 错误对象
   */
  error(res, message, statusCode = StatusCodes.BAD_REQUEST, error = null) {
    // 确保logger存在并且有error方法
    try {
      const currentLogger = (this.logger && this.logger.error) ? this.logger : logger;
      
      if (error && currentLogger && currentLogger.error) {
        currentLogger.error(`${message}: ${error.message}`, { error });
      } else if (currentLogger && currentLogger.error) {
        currentLogger.error(message);
      }
    } catch (logError) {
      // 如果日志记录失败，使用console.error作为备用
      console.error('Logger error:', logError);
      console.error('Original error:', error);
    }

    res.status(statusCode).json({
      success: false,
      message,
      error: error ? {
        name: error.name,
        message: error.message,
        ...(process.env.NODE_ENV === 'development' ? { stack: error.stack } : {})
      } : undefined
    });
  }

  /**
   * 创建资源
   */
  async create(req, res) {
    try {
      const data = await this.service.create(req.body);
      this.success(res, data, '创建成功', StatusCodes.CREATED);
    } catch (error) {
      this.error(res, '创建失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 获取所有资源
   */
  async getAll(req, res) {
    try {
      const { page = 1, limit = 10, ...query } = req.query;
      const result = await this.service.findAll({
        where: query,
        offset: (page - 1) * limit,
        limit: parseInt(limit, 10),
      });
      this.success(res, result, '获取成功');
    } catch (error) {
      this.error(res, '获取失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 根据ID获取资源
   */
  async getById(req, res) {
    try {
      const { id } = req.params;
      const data = await this.service.findById(id);
      
      if (!data) {
        return this.error(res, '资源不存在', StatusCodes.NOT_FOUND);
      }
      
      this.success(res, data, '获取成功');
    } catch (error) {
      this.error(res, '获取失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 更新资源
   */
  async update(req, res) {
    try {
      const { id } = req.params;
      const data = await this.service.update(id, req.body);
      
      if (!data) {
        return this.error(res, '资源不存在', StatusCodes.NOT_FOUND);
      }
      
      this.success(res, data, '更新成功');
    } catch (error) {
      this.error(res, '更新失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }

  /**
   * 删除资源
   */
  async delete(req, res) {
    try {
      const { id } = req.params;
      const success = await this.service.delete(id);
      
      if (!success) {
        return this.error(res, '资源不存在', StatusCodes.NOT_FOUND);
      }
      
      this.success(res, null, '删除成功');
    } catch (error) {
      this.error(res, '删除失败', StatusCodes.INTERNAL_SERVER_ERROR, error);
    }
  }
}

export default BaseController;
